import {createBindingEditorOptionUser, createCmsEditorOptionUser, createRuleEditorOptionUser, iRuleRecord, iRunningOptionConfig, nextCmsId, PlainRuleNamespace} from "../../../packages";
import {env} from "../../env";
import {$loading, $notice, i18n} from "plain-design";
import {QueryBindingVariableData} from "./QueryBindingVariableData";
import {http} from "../plain-design/http";
import {upload} from "../plain-design/upload";
import {pathJoin} from "@peryl/utils/pathJoin";

export const DefaultQueryRuleRecords: iRunningOptionConfig['queryRuleRecords'] = async (ruleRecordId?: string): Promise<any> => {
  if (!ruleRecordId) {
    /*查询所有可用规则*/
    const resp = await http.post<{ list: iRuleRecord[] }>('/rule/list', { all: true, orders: [{ field: 'createdAt', desc: true }] });
    return resp.list;
  } else {
    /*根据id查询单条规则*/
    const resp = await http.post<{ result: iRuleRecord }>('/rule/item', { id: ruleRecordId });
    return resp.result;
  }
};

export const DefaultEditorConfig = {
  useRuleEditorOptionGetter: () => useRuleEditorOption,
  useCmsEditorOptionGetter: () => useCmsEditorOption,
};

export const DefaultRunningConfig: Omit<iRunningOptionConfig, 'isRunning'> = {
  i18n,
  queryBindingVariableData: QueryBindingVariableData,
  queryRuleRecords: DefaultQueryRuleRecords,
  handleVariableDependencyError: (e) => {$notice.error(JSON.stringify(e.message || e));},
};

export const useCmsEditorOption = createCmsEditorOptionUser({
  runningOptionConfig: DefaultRunningConfig,
  editorOptionConfig: DefaultEditorConfig,
  assetsPrefix: env.assetsPrefix,
  getSnapshot: async ({ file }) => {
    const closeLoading = $loading();
    return new Promise<string>((resolve, reject) => {
      upload.upload({
        file,
        action: pathJoin(env.baseURL, 'saveFile'),
        filename: 'file',
        data: { headId: '1', attr1: '2' },
        onSuccess: (resp: any) => {
          resolve(pathJoin(env.assetsPrefix, resp.result.path));
          closeLoading();
        },
        onError: () => {
          reject();
          closeLoading();
        },
      });
    });
  },
});

useCmsEditorOption.use(option => {

  option.hooks.onError.use((e) => {
    const msg = e.message || JSON.stringify(e);
    $notice.error(msg);
  });

});

export const useBindingEditorOption = createBindingEditorOptionUser({
  ...DefaultRunningConfig,
  editorOptionConfig: DefaultEditorConfig,
});

export const DefaultRuleEditorConfig: PlainRuleNamespace.iDefaultConfig = {
  htlSpace: 56,
  vtlSpace: 24,
  strokeWidth: 1,
  buttonSize: 18,
  spaceBetweenNodeAndButton: 4,
  spaceBetweenNodeAndEdge: 4,
  runningOptionConfig: DefaultRunningConfig,
  editorOptionConfig: DefaultEditorConfig,
};

export const useRuleEditorOption = createRuleEditorOptionUser({
  ...DefaultRuleEditorConfig,
});
